<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :configFixed="{ flag: 'right' }" :dataList="dataList"
        :loading="loading" @selection-change="selectionChange">
        <template v-slot:lookFacilityList="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="lookFacilityList(row)">
            <i class="el-icon-view"></i> 查看
          </el-button>
        </template>
        <template v-slot:message="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="lookMessage(row)">
            <i class="el-icon-view"></i> 查看告警详情
          </el-button>
        </template>
        <template v-slot:disposeStatus="{ row }">
          {{ row.disposeStatus ? '已处理' : '未处理' }}
        </template>
      </TableData>
      <!-- <div class="tabsList">
        <el-tabs type="border-card" v-model="disposeStatus" @tab-click="handleClick">
          <el-tab-pane label="待处理" name="0">
            <TableData :config="table_config" :tableThead="tableThead" :configFixed="{ flag: 'right' }"
              :dataList="dataList" :loading="loading" @selection-change="selectionChange">
              <template v-slot:lookFacilityList="{ row }">
                <el-button class="text-btn-cursor" type="text" size="small" @click="lookFacilityList(row)">
                  <i class="el-icon-view"></i> 查看
                </el-button>
              </template>
              <template v-slot:message="{ row }">
                <el-button class="text-btn-cursor" type="text" size="small" @click="lookMessage(row)">
                  <i class="el-icon-view"></i> 查看告警详情
                </el-button>
              </template>
              <template v-slot:disposeStatus="{ row }">
                {{ row.disposeStatus ? '已处理' : '未处理' }}
              </template>
            </TableData>
          </el-tab-pane>
          <el-tab-pane label="已处理" name="1">
            <TableData :tableThead="tableThead" :dataList="dataList" :loading="loading" 
              @selection-change="selectionChange">
              <template v-slot:lookFacilityList="{ row }">
                <el-button class="text-btn-cursor" type="text" size="small" @click="lookFacilityList(row)">
                  <i class="el-icon-view"></i> 查看
                </el-button>
              </template>
              <template v-slot:message="{ row }">
                <el-button class="text-btn-cursor" type="text" size="small" @click="lookMessage(row)">
                  <i class="el-icon-view"></i> 查看告警详情
                </el-button>
              </template>
              <template v-slot:disposeStatus="{ row }">
                {{ row.disposeStatus ? '已处理' : '未处理' }}
              </template>
            </TableData>
          </el-tab-pane>
        </el-tabs>
      </div> -->

    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'处理信息'" :unitList="unitList" :varietyList="varietyList" @closeDialog="closeDialog"
        :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
      <el-dialog :close-on-click-modal="false" title="查看" :visible.sync="isShowEquip" width="60%"
        :before-close="() => { isShowEquip = false }">
        <div class="facilityBOList" v-show="!messageFlag">
          <div class="facility" v-for="item in facilityBOList">
            <div class="item"> <span>设施名称:</span> {{ item.facilityName }}</div>
            <div class="item"> <span>设施编号:</span> {{ item.facilityNo }}</div>
          </div>
        </div>
        <div v-show="messageFlag">
          {{ messageInfo }}
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowEquip = false">关 闭</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import alarmHandling from '@/api/monitoringAlarmManagement/alarmHandling.js';

import alarmCategoryManagement from '@/api/monitoringAlarmManagement/alarmCategoryManagement.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import batch from '@/api/batch/batchManagement';


export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      unfoldFlag: false,
      isShowEquip: false,
      disposeStatus: '0',
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      addEditFlag: 'add',
      selectList: [],
      facilityBOList: [],
      unitList: [],
      formData: {},
      page: 1,
      size: 10,
      total: 100,
      selectIndex: 0,
      searchFormData: {
        disposeStatus: false
      },
      btnList: ['add', 'delete'],
      dataList: [],
      tableThead: [
        { isShow: true, prop: "batchName", label: "批次名称", minWidth: "200" },
        {
          isShow: true,
          prop: "lookFacilityList",
          label: "设施列表",
          slotName: "lookFacilityList"
        },
        { isShow: true, prop: "baseAlarmName", label: "告警名称", minWidth: "200" },
        { isShow: true, prop: "dataItemName", label: "告警数据项", minWidth: "150" },
        { isShow: true, prop: "alarmPresetValue", label: "预设告警值", minWidth: "150" },
        { isShow: true, prop: "actualAlarmValue", label: "实际告警值", minWidth: "150" },
        { isShow: true, prop: "generateTime", label: "发生时间", minWidth: "150" },
        { isShow: true, prop: "dataTypeName", label: "环境数据类型", minWidth: "150" },
        { isShow: true, prop: "alarmTypeName", label: "告警数据类型", minWidth: "200" },
        { isShow: true, slotName: "message", label: "详情", minWidth: "150" },
        {
          isShow: true, prop: "disposeStatus",
          label: "告警信息状态",
          slotName: "disposeStatus",
          minWidth: "150",
        },
        // { isShow: true, prop: "disposeContent", label: "处理意见" },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '处理',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            }
          ]
        },
      },
      varietyList: [],
      messageInfo: '',
      messageFlag: false,
      formItemList: [
        {
          label: '选择批次',
          type: 'select',
          selectOptions: [],
          param: 'batchName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '告警数据类型',
          type: 'select',
          selectOptions: [],
          param: 'alarmTypeId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '数据类型',
          type: 'select',
          selectOptions: [],
          param: 'dataTypeId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      batchList: [],
      facilityList: [],
      alarmCategoryTypeList: [],
      datalist: [],
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      //数据类型
      let { data: datalist } = await alarmCategoryManagement.getalldatalist({})
      this.datalist = datalist;
      console.log(datalist)
      //告警数据类型
      let { data: alarmCategoryTypeList } = await alarmCategoryManagement.querybycondition({})
      this.alarmCategoryTypeList = alarmCategoryTypeList
      console.log(alarmCategoryTypeList)
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' })
      this.batchList = batchList
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param == 'facilityNo') {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityNo
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'batchName') {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'alarmTypeId') {
          let selectOptions = this.alarmCategoryTypeList.map(data => {
            return {
              text: data.alarmTypeName, value: data.alarmTypeId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'dataTypeId') {
          let selectOptions = this.datalist.map(data => {
            return {
              text: data.dataTypeName, value: data.dataTypeId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    lookMessage(row) {
      this.messageFlag = true;
      this.messageInfo = row.message || '';
      this.isShowEquip = true;
    },
    handleClick() {
      this.searchFormData.disposeStatus = this.disposeStatus == '0' ? false : true;
      this.queryPageByCondition();
    },
    delList(deleteList = [], key = 'checkStageId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await alarmHandling.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          simpleEntity: false
        }
      }
      alarmHandling.getlist(params, this.searchFormData.disposeStatus).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          console.log(this.total)
          if (res.totalPages && this.page > res.totalPages) {
            this.page = res.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 查看设施列表
    lookFacilityList(row) {
      this.facilityBOList = row.facilityList;
      this.messageFlag = false;
      this.isShowEquip = true;
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
.facilityBOList {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;

  .facility {
    padding: 10px 30px;
    margin: 5px;
    box-shadow: 0 0 10px 5px #cecece4d;
    border-radius: 6px;
    border: 1px solid #cecece63;

    .item {
      line-height: 24px;

      span {
        font-weight: bold;
      }
    }
  }
}

.tabsList {
  height: 100%;
  overflow: auto;
}

::v-deep .el-tabs--border-card {
  height: 100%;
  overflow: hidden;
}
</style>